<template>
  <div style="padding: 10px">
    <!--标题-->
    <div style="margin: 10px 0">
      <div><h3 style="text-align: center">任务录入</h3></div>
    </div>
    <!--    搜索区-->
    <div style="margin: 10px 0">
      <!--时间搜索-->
      <el-input v-model="search" placeholder="格式（2023年-1周）" clearable style="width: 15%" />
      <el-button type="primary" style="margin-left: 5px" @click="search_time">查询</el-button>
      <!--分组搜索-->
      <el-select v-model="select" filterable placeholder="组别分类" :remote-method="search_group" style="width: 20%;padding-left: 40px">
        <el-option label="开发组" value="开发组" />
        <el-option label="提高组" value="提高组" />
        <el-option label="学习组" value="学习组" />
        <el-option label="所有组" value="" />
      </el-select>
      <!--搜索返回按钮-->
      <el-button v-if="fanHuiShow" type="primary" @click="fanHui" style="margin-left: 40px;" round> 返 回 </el-button>

      <!--    功能区-->
      <el-button type="primary" style="margin-right: 10px;float: right" @click="task_add">添加任务</el-button>
    </div>
    <!--    任务卡片-->
    <div style="margin: 30px auto 140px;display:flex;">
      <ul style="flex: 1;"
          v-infinite-scroll="load"
          infinite-scroll-delay="500"
          infinite-scroll-disabled="busy"
          infinite-scroll-immediate="false"
          infinite-scroll-distance='1'>
        <TaskItem v-for="a in tasks" @click="view(a.id)" :key="a.id" v-bind="a" />
      </ul>
    </div>
    <!--  添加任务  -->
    <div>
      <el-dialog v-model="show" title="添加任务" width="80%">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
           <el-form-item label="组别" prop="group" >
              <el-radio v-model="form.group" label="开发组">开发组</el-radio>
              <el-radio v-model="form.group" label="提高组">提高组</el-radio>
              <el-radio v-model="form.group" label="学习组">学习组</el-radio>
           </el-form-item>
          <el-form-item label="详细分组" style="float: left" prop="group_detail">
            <el-input v-model="form.group_detail" style="width: 60%;height: 30px;font-size: 18px" />
          </el-form-item>
          <el-form-item label="任务时间"  prop="year_week">
            <el-input v-model="form.year_week" style="width: 25%;height: 30px;font-size: 18px" />
          </el-form-item>
          <el-form-item label="任务简介" prop="task_introduction">
            <el-input v-model="form.task_introduction" style="width: 90%;height: 40px;font-size: 20px" />
          </el-form-item>
          <div id="editor—wrapper">
            <!--            工具栏-->
            <div id="toolbar-container"></div>
            <!--            编辑框-->
            <div id="editor-container"></div>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="show = false">取 消</el-button>
            <el-button type="primary" @click="task_save">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import TaskItem from "@/components/taskItem";
import '@wangeditor/editor/dist/css/style.css';
import { createEditor, createToolbar } from '@wangeditor/editor';

let editor;
export default {
  name: 'Task',
  components: {
    TaskItem,
  },
  data() {
    return{
      rules: {
        group: [
          {required: true, message: '内容不能为空', trigger: 'blur',},
        ],
        group_detail: [
          {required: true, message: '内容不能为空', trigger: 'blur'},
        ],
        year_week: [
          {required: true, message: '时间不能为空', trigger: 'blur'},
          { pattern: /^(\d{4})年-(\d{1,2})周$/, message: '时间格式：xxxx年-x周', trigger: 'blur' }
        ],
        task_introduction: [
          {required: true, message: '内容不能为空', trigger: 'blur'},
        ]
      },
      form:{},
      show:false,
      tasks:[],
      search:"",
      select:"",
      busy: false,
      page: 1, // 记录页面数
      totalPage:1, // 数据 总页数
      currentPage: 1, // 当前页码
      pageSize: 8, // 一页 数据大小
      fanHuiShow: false,
    }
  },
  created() { //页面加载 调用
    this.getData()
  },
  methods: {
    // 搜索后返回总数居
    fanHui() {
      // 刷新页面
      window.location.reload();
    },
    task_save() {
      // 获取 编辑器中的内容 1
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.task_content = editor.getHtml();
          request.post("/task/add", this.form).then(res => {
            if (res.code == 200) {
              ElMessage({
                message: '添加成功',
                type: 'success',
              })
              console.log(res.data)
              this.form={};   //重置表格对象
            } else {
              ElMessage.error('添加失败: '+res.msg)
            }
            this.getData()
            this.show = false
          })
        }
      })
    },
    //点击标题进入详细页面 1
    view(id) {
      this.$router.push({path: `/task/${id}`})
    },
    // 打开文本编辑器弹窗 1
    task_add() {
      this.show = true
      if (!editor) { // 避免 重复创建相同id 的 编辑器
        this.editor_create()
      }else {
        editor.destroy()
        this.editor_create()
      }
    },

    // 创建富文本编辑器 1
    editor_create() {
      this.$nextTick(()=> { //执行延迟回调 ,避免异步找不到dom
        const editorConfig = {
          placeholder: '具体任务内容',
          // 上传本地图片配置
          MENU_CONF: {
            uploadImage: {
              fieldName: "file",
              server: "http://"+window.server.filesUploadUrl+":8081/files/editor/upload",
              // server: 'http://localhost:8081/files/editor/upload',
            },
            uploadVideo: {
              fieldName: "file",
              server: "8081/files/editor/uploadVideo",
              maxFileSize: 500 * 1024 * 1024, // 500M
              // 上传之前触发
              onBeforeUpload(file) {
                ElMessage({
                  message: '该功能未推出，敬请期待！',
                  type: 'info',
                })
                return false
              },
            }
          }
        }
        // 创建编辑器
        editor = createEditor({
          selector: '#editor-container',
          config: editorConfig,
        })
        // 创建工具栏
        const toolbar = createToolbar({
          editor,
          selector: '#toolbar-container'
        })
      })
    },
    // 时间搜索 1
    search_time() {
      if (!this.fanHuiShow) {
        this.fanHuiShow = true;
      }
      request.get("/task/search",{
        params:{
          url:"/task",
          time:this.search,
          group:this.select
        }
      }).then(res => {
        if (res.code == "200") {
          this.tasks = res.data
          ElMessage({
            message: '搜索成功.',
            type: 'success',
          })
        } else if (res.code == "400"){
          ElMessage.error('暂无数据')
        }
        else if (res.code == "load"){
          this.load()
        }
        else {
          ElMessage.error('搜索失败：'+res.msg)
        }
      })
    },
    // 组别搜索 1
    search_group() {
      if (!this.fanHuiShow) {
        this.fanHuiShow = true;
      }
      request.get("/task/search",{
        params:{
          url:"/task",
          group:this.select
        }
      }).then(res => {
        if (res.code == "200") {
          this.tasks = res.data
          ElMessage({
            message: '搜索成功.',
            type: 'success',
          })
        } else if (res.code == "400"){
          ElMessage.error('暂无数据')
        }
        else if (res.code == "load"){
          this.load()
        }
        else {
          ElMessage.error('搜索失败：'+res.msg)
        }
      })
    },
    // 获取数据总数 1
    getTotal() {
      request.get("/task/get_task_num",{
        params:{
          url:"/task",
        }
      }).then(res => {
        // 获取总页数
        if (res.data % 8 == 0) {
          // 总条数 刚好是 页数的倍数
          this.totalPage = res.data / 8
        }else {
          // 总条数 不是 页数的倍数
          this.totalPage = ((res.data - (res.data % 8)) /8) + 1
        }
      })
    },
    // 回调加载更多数据 1
    load() {
      // 获取总页面数
      this.getTotal()
      this.busy=true
      setTimeout(() => {
        // 当前页数如果小于总页数，则继续请求数据，如果大于总页数，则滚动加载停止
        if (this.currentPage < this.totalPage) {
          //  这里是列表请求数据的接口,在这个接口中更新总页数
          this.getData()
        } else {
          this.busy = true
        }
        this.busy = false
      }, 1000)
    },
    // 获取任务数据 1
    getData() {
      // 更新当前页面
      this.currentPage = this.page
      request.get("/task/get_task",{
        params:{
          url:"/task",
          limit: this.pageSize*this.currentPage,
          order:"id.desc"
        }
      }).then(res => {
        if (res.code == "400") {
          ElMessage.warning('暂无数据')
        }else if (res.code == "200") {
          this.busy = false
          this.tasks = res.data
          if (this.page<=1) {
            ElMessage.success("查询成功")
          }
          this.page++
        }
        else {
          ElMessage.error('查询失败：'+res.msg)
        }
      })
    }
  },

}
</script>
